from django.db.models import Sum, Q
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import authenticate, login, logout
from utils.ipagination import Page
from utils.jwt_token import generate
from utils.time import getCurrentTime
from trade.utils import get_cost_price
from django.conf import settings
from trade.models import Trade, Agent, User, SentTradeDetails, ReturnTradeDetails, CostDetails
from utils.permissions import IsCommonAdminUser, IsTreasurerAdminUser, IsManagerAdminUser, Check
from after.models import ReturnFrom, ReturnDevice, ReissuePB
from after.utils import getDevices, getTag

import json
import time


# Create your views here.

# trade/reset/
class ResetPWDAPIView(APIView):
    """修改密码"""

    def post(self, request):
        resp = {'code': 200, 'msg': '修改成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        if 'username' and 'password' not in req:
            resp['code'] = 400
            resp['msg'] = '请输入用户名和密码！'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        username = req['username']
        password = req['password']

        try:
            user = User.objects.get(username=username)
            user.set_password(password)
            user.save()

        except Exception as e:
            print(e)
            resp['code'] = 400
            resp['msg'] = '修改失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


# trade/register/
class RegisterAPIView(APIView):
    """注册"""

    def post(self, request):
        resp = {'code': 200, 'msg': '注册成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        if 'username' and 'password' not in req:
            resp['code'] = 400
            resp['msg'] = '请输入用户名和密码！'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        username = req['username']
        password = req['password']
        user_type = req['user_type'] if 'user_type' in req else 1

        try:
            user = User.objects.create(username=username, user_type=user_type)
            user.set_password(password)
            user.save()

        except:
            resp['code'] = 400
            resp['msg'] = '注册失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


# trade/login/

class LoginAPIView(APIView):
    """后台登录"""

    def post(self, request):
        resp = {'code': 200, 'msg': '登录成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        if 'username' and 'password' not in req:
            resp['code'] = 400
            resp['msg'] = '请输入用户名和密码！'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        username = req['username']
        password = req['password']

        if not username or not password:
            resp['code'] = 400
            resp['msg'] = '请求参数错误~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        user = authenticate(request, username=username, password=password)

        if not user:
            resp['code'] = 400
            resp['msg'] = '账号或密码错误~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        if user.user_type not in [1, 2, 3]:
            resp['code'] = 400
            resp['msg'] = '此账户不是后台账户~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        login(request, user)

        resp['data'] = {
            'id': user.id,
            'username': user.username,
            'userType': user.user_type,
            'token': generate(user)
        }
        return Response(resp, status.HTTP_200_OK)


# /trade/logout/
class LogoutAPIView(APIView):
    """后台登出"""

    def post(self, request):
        resp = {'code': 200, 'msg': '登出成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        logout(request)
        return Response(resp)


# /trade/agent/save/

class SaveAgentAPIView(APIView):
    """添加/修改代理"""
    permission_classes = [IsAuthenticated, IsCommonAdminUser]

    def post(self, request):
        resp = {'code': 200, 'msg': '添加成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        customer_name = req['agent_name'] if 'agent_name' in req else ''
        mobile = req['mobile'] if 'mobile' in req else ''
        if not customer_name:
            resp['code'] = 400
            resp['msg'] = '请填写代理商名称~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)
        # 修改
        try:
            id = req['id']
            try:
                agent = Agent.objects.get(id=id, status=1)
                agent.customer_name = customer_name
                agent.mobile = mobile
                agent.update_time = getCurrentTime()
                agent.save()
                resp['msg'] = '修改成功'
                resp['data']['agentId'] = agent.id
                resp['data']['agent_name'] = agent.customer_name
                resp['data']['mobile'] = agent.mobile

            except:
                resp['code'] = 400
                resp['msg'] = '该代理不存在~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        # 添加
        except:
            if Agent.objects.filter(customer_name=customer_name, status=1, mobile=mobile).exists():
                resp['code'] = 400
                resp['msg'] = '该代理已存在~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

            else:
                agent = Agent.objects.create(customer_name=customer_name, mobile=mobile)
                resp['data']['agentId'] = agent.id
                resp['data']['agent_name'] = agent.customer_name
                resp['data']['mobile'] = mobile

        return Response(resp)


# /trade/agent/del/{agentId}
class DelAgentAPIView(APIView):
    """删除代理"""
    permission_classes = [IsAuthenticated, IsCommonAdminUser]

    def post(self, request, pk):
        resp = {'code': 200, 'msg': '删除成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        try:
            agent = Agent.objects.get(id=pk, status=1)
        except:
            resp['code'] = 400
            resp['msg'] = '该代理不存在~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        agent.delete()
        return Response(resp)


# /trade/agent/list/
class ListAgentAPIView(APIView):
    """代理列表"""

    def get(self, request):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = request.GET

        page = req['page'] if 'page' in req else 0
        page_size = req['page_size'] if 'page_size' in req else 15
        search = req['search'] if 'search' in req else ''

        resp['data']['agents'] = []

        agent_obj = Agent.objects.filter(customer_name__contains=search, status=1).order_by("-id")

        if page != 0:
            agents, pages = Page(page, page_size, agent_obj)
            resp['data']['pages'] = pages
        else:
            agents = agent_obj.all()

        for agent in agents:
            trades = Trade.objects.filter(agent=agent, status=1, finance_check=1, manager_check=1).all()
            total = trades.aggregate(Sum('price'), Sum('collection'), Sum('no_collection'), Sum('profits'),
                                     Sum('out_fare'), Sum('in_fare'), Sum('generated_commission'), Sum('no_commission'),
                                     Sum('generated_cost'), Sum('no_cost'))
            total_price = total['price__sum'] if total['price__sum'] else 0
            total_collection = total['collection__sum'] if total['collection__sum'] else 0
            total_no_collection = total['no_collection__sum'] if total['no_collection__sum'] else 0
            total_profits = total['profits__sum'] if total['profits__sum'] else 0
            total_out_fare = total['out_fare__sum'] if total['out_fare__sum'] else 0
            total_in_fare = total['in_fare__sum'] if total['in_fare__sum'] else 0
            total_generated_commission = total['generated_commission__sum'] if total['generated_commission__sum'] else 0
            total_no_commission = total['no_commission__sum'] if total['no_commission__sum'] else 0
            total_generated_cost = total['generated_cost__sum'] if total['generated_cost__sum'] else 0
            total_no_cost = total['no_cost__sum'] if total['no_cost__sum'] else 0
            resp['data']['agents'].append(
                {"key": agent.id, "agentName": agent.customer_name, "price": total_price,
                 "collection": total_collection,
                 "no_collection": total_no_collection, "profits": total_profits, "out_fare": total_out_fare,
                 "in_fare": total_in_fare, "generated_commission": total_generated_commission,
                 "no_commission": total_no_commission, "generated_cost": total_generated_cost,
                 "no_cost": total_no_cost
                 })

        return Response(resp)


# /trade/list/{id}
class ListTradeAPIView(APIView):
    """交易列表"""
    permission_classes = [IsAuthenticated]

    def post(self, request, id):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        resp['data']['trades'] = []

        tag = req['tag'] if 'tag' in req else 1
        tag = int(tag)

        search = req['search'] if 'search' in req else ''
        try:
            agent = Agent.objects.get(id=id, status=1)
        except:
            resp['code'] = 400
            resp['msg'] = '该代理不存在~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        page = req['page'] if 'page' in req else 0
        page_size = req['page_size'] if 'page' in req else 15

        if search:
            trades = Trade.objects.filter(agent=agent, date__in=search)

        else:
            trades = Trade.objects.filter(agent=agent)

        trades = trades.order_by('date')

        if tag == 1:
            trades = trades.filter(status=1)

        elif tag == 2:
            trades = trades.exclude(finance_check=1, manager_check=1).filter(status=1)

        elif tag == 3:
            trades = trades.filter(finance_check=1, manager_check=1, status=1)

        elif tag == 4:
            trades = trades.filter(status=2)

        else:
            resp['code'] = 400
            resp['msg'] = '类型错误~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        if page != 0:
            data, pages = Page(page, page_size, trades)

            resp['data']['pages'] = pages

        else:
            trades = trades.all()

        for trade in trades:
            resp['data']['trades'].append({
                'tradeId': trade.id,
                'date': trade.date,
                'count': trade.count,
                'unshippedQuantity': trade.no_deliver_count,
                'price': trade.price,
                'equipment': trade.equipment,
                'collection': trade.collection,
                'no_collection': trade.no_collection,
                'profits': trade.profits,
                'generated_commission': trade.generated_commission,
                'no_commission': trade.no_commission,
                'generated_cost': trade.generated_cost,
                'no_cost': trade.no_cost,
                'out_fare': trade.out_fare,
                'in_fare': trade.in_fare,
                'fiance_check': trade.finance_check,
                'manager_check': trade.manager_check,
                'status': trade.status
            })

        return Response(resp)


# trade/save/
class SaveTradeAPIView(APIView):
    """添加或修改交易信息"""
    permission_classes = [IsAuthenticated, IsCommonAdminUser]

    def post(self, request):
        resp = {'code': 200, 'msg': '添加成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)

        # 价目表
        eq_cost = get_cost_price()
        # 编辑
        try:
            id = req['id']
            try:
                trade = Trade.objects.get(id=id, status=1, finance_check=1, manager_check=1)
                trade.date = req['date'] if 'date' in req else trade.date
                trade.collection = req['collection'] if 'collection' in req else trade.collection
                trade.no_collection = trade.price - trade.collection
                if trade.no_collection < 0:
                    resp['code'] = 400
                    resp['msg'] = '已收金额大于总金额~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
                trade.generated_commission = req[
                    'generated_commission'] if 'generated_commission' in req else trade.generated_commission
                trade.no_commission = req[
                    'no_commission'] if 'no_commission' in req else trade.no_commission
                trade.profits = trade.collection - trade.generated_cost - trade.out_fare - trade.in_fare - trade.generated_commission
                trade.update_time = getCurrentTime()
                trade.finance_check = False
                trade.manager_check = False
                trade.save()
                resp['msg'] = '修改成功~'

            except Exception as e:
                print(e)
                resp['code'] = 400
                resp['msg'] = '该交易明细不存在或在审核中~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        # 添加
        except:
            try:
                try:
                    agentId = req['agentId']
                except:
                    resp['code'] = 400
                    resp['msg'] = '代理商id缺失~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
                date = req['date']
                price = req['price']
                equipment = req['equipment']
                if equipment not in ['0', '1', '2', '3', '4', '5', '6']:
                    resp['code'] = 400
                    resp['msg'] = '无该设备~'
                    resp['success'] = False
                count = req['count']
                collection = req['collection']
                no_collection = price - collection
                if no_collection < 0:
                    resp['code'] = 400
                    resp['msg'] = '已收金额大于总金额~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
                generated_commission = req['generated_commission']
                no_commission = req['no_commission']
                no_cost = eq_cost[equipment] * count
                profits = collection - generated_commission

            except Exception as e:
                resp['code'] = 400
                resp['msg'] = '参数错误~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
            try:
                agent = Agent.objects.get(id=agentId)
                Trade.objects.create(date=date, price=price, equipment=equipment, count=count,
                                     collection=collection, no_collection=no_collection,
                                     create_time=getCurrentTime(), update_time=getCurrentTime(),
                                     agent=agent, no_deliver_count=count, generated_commission=generated_commission,
                                     no_commission=no_commission, no_cost=no_cost, profits=profits)
            except:
                resp['code'] = 400
                resp['msg'] = '新建失败~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


# trade/del/{id}/
class DelTradeAPIView(APIView):
    """删除交易信息"""
    permission_classes = [IsAuthenticated, IsCommonAdminUser]

    def post(self, request, pk):
        resp = {'code': 200, 'msg': '删除成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        agentId = req['agentId'] if 'agentId' in req else ''
        if not agentId:
            resp['code'] = 400
            resp['msg'] = '请输入代理id~'
            resp['success'] = False
            return Response(resp, status=status.HTTP_400_BAD_REQUEST)
        try:
            agent = Agent.objects.get(id=agentId, status=1)
            trade = Trade.objects.get(id=pk, agent=agent, status=1)
            try:
                if SentTradeDetails.objects.filter(trade=trade, status=1).exists() or ReturnTradeDetails.objects.filter(
                        trade=trade, status=1).exists():
                    resp['code'] = 400
                    resp['msg'] = '已存在发/退货记录，无法删除~'
                    resp['success'] = False
                    return Response(resp, status=status.HTTP_400_BAD_REQUEST)
                else:
                    trade.delete()
            except:
                resp['code'] = 400
                resp['msg'] = '删除失败~'
                resp['success'] = False
                return Response
        except:
            resp['code'] = 400
            resp['msg'] = '无该条明细~'
            resp['success'] = False
            return Response
        return Response(resp)


# trade/sent/
class SentAPIView(APIView):
    """发货"""
    permission_classes = [IsAuthenticated, IsCommonAdminUser]

    def post(self, request):
        resp = {'code': 200, 'msg': '发货成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        date = req['date'] if 'date' in req else getCurrentTime(format="%Y-%m-%d")
        # 运费
        sent = req['sent'] if 'sent' in req else 0
        count = req['count'] if 'count' in req else 0
        tradeId = req['tradeId'] if 'tradeId' in req else ''
        remark = req['remark'] if 'remark' in req else ''

        eq_cost = get_cost_price(date)

        try:
            try:
                trade = Trade.objects.get(id=tradeId, status=1, finance_check=True, manager_check=True)
                equipment = trade.equipment
                cost = eq_cost[equipment] * trade.count
                if count > trade.no_deliver_count:
                    resp['code'] = 400
                    resp['msg'] = '发货数超过剩余未发货总数~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                print(e)
                resp['code'] = 400
                resp['msg'] = '该交易明细不存在或在审核中~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

            generated_cost = count * eq_cost[equipment]
            SentTradeDetails.objects.create(date=date, equipment=equipment, count=count, sent=sent, cost=generated_cost,
                                            trade=trade, remark=remark)

            trade.generated_cost += generated_cost
            trade.no_cost = cost - trade.generated_cost
            trade.no_deliver_count -= count
            trade.out_fare += sent
            trade.profits = trade.collection - trade.generated_cost - trade.out_fare - trade.in_fare - trade.generated_commission
            trade.finance_check = False
            trade.manager_check = False
            trade.save()
        except Exception as e:
            print(e)
            resp['code'] = 400
            resp['msg'] = '发货失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


# trade/return/
class ReturnAPIView(APIView):
    """退货"""
    permission_classes = [IsAuthenticated, IsCommonAdminUser]

    def post(self, request):
        resp = {'code': 200, 'msg': '退货成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        date = req['date'] if 'date' in req else getCurrentTime(format="%Y-%m-%d")
        # 运费
        fare = req['back'] if 'back' in req else 0
        count = req['count'] if 'count' in req else 0
        returnType = req['returnType'] if 'returnType' in req else "1"
        tradeId = req['tradeId'] if 'tradeId' in req else ''
        remark = req['remark'] if 'remark' in req else ''

        eq_cost = get_cost_price()

        # returnTypeDict = {
        #     "1": '退换货',
        #     "2": '退货退款',
        #     "3": '退钱'
        # }
        try:
            try:
                trade = Trade.objects.get(id=tradeId, status=1, finance_check=True, manager_check=True)
                if count > trade.count - trade.no_deliver_count:
                    resp['code'] = 400
                    resp['msg'] = '退货数超过已发货数量~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
            except:
                resp['code'] = 400
                resp['msg'] = '没有该条交易明细~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

            equipment = trade.equipment

            if returnType == "1":
                trade.in_fare += fare
                trade.no_deliver_count += count
                trade.generated_cost -= eq_cost[equipment] * count
                trade.no_cost += eq_cost[equipment] * count
                trade.profits = trade.collection - trade.generated_cost - trade.out_fare - trade.in_fare - trade.generated_commission
                trade.finance_check = False
                trade.manager_check = False
                cost = fare
                trade.save()

            elif returnType == "2":
                price = req['price'] if 'price' in req else 0
                trade.in_fare += fare
                trade.count -= count
                trade.generated_cost -= eq_cost[equipment] * count
                if price > trade.price:
                    resp['code'] = 400
                    resp['msg'] = '退货退款金额不正确~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
                trade.price -= price
                if price >= trade.collection:
                    trade.collection = 0
                    trade.no_collection = trade.price

                else:
                    trade.collection = trade.price - trade.no_collection

                trade.profits = trade.collection - trade.generated_cost - trade.out_fare - trade.in_fare - trade.generated_commission
                trade.finance_check = False
                trade.manager_check = False

                cost = fare

                trade.save()

            elif returnType == "3":
                price = req['price'] if 'price' in req else 0
                trade.in_fare += fare
                cost = eq_cost[equipment] * count + fare

                if price > trade.collection:
                    resp['code'] = 400
                    resp['msg'] = '仅退款金额过大~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)

                trade.price -= price
                trade.collection = trade.price - trade.no_collection
                trade.finance_check = False
                trade.manager_check = False
                trade.save()

            else:
                resp['code'] = 400
                resp['msg'] = '退款类型不存在~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

            ReturnTradeDetails.objects.create(date=date, equipment=equipment, count=count, return_fare=fare,
                                              trade=trade, cost=cost, remark=remark, classes=returnType)

        except Exception as e:
            print(e)
            resp['code'] = 400
            resp['msg'] = '退货失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


# trade/record/{id}
class RecordAPIView(APIView):
    """发货/退货记录"""

    def get(self, request, id):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        type = request.GET.get('type')
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')

        resp['data']['records'] = []

        if not type:
            type = '1'

        if page:
            page = int(page)
        else:
            page = 0
        if page_size:
            page_size = int(page_size)
        else:
            page_size = 15

        try:
            trade = Trade.objects.get(id=id, status=1)
            if type == '1':
                Records = SentTradeDetails.objects.filter(trade=trade, status=1)
            elif type == '2':
                Records = ReturnTradeDetails.objects.filter(trade=trade, status=1)
            else:
                resp['code'] = 400
                resp['msg'] = '类型错误~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

        except:
            resp['code'] = 400
            resp['msg'] = '查询失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        if page != 0:
            records, pages = Page(page, page_size, Records)
            resp['data']['pages'] = pages

        else:
            records = Records.all()

        if type == '1':
            for record in records:
                resp['data']['records'].append({
                    'date': record.date,
                    'equipment': settings.EQUIPMENT[record.equipment],
                    'count': record.count,
                    'cost': record.cost,
                    'remark': record.remark,
                    'fare': record.sent
                })
        elif type == '2':
            for record in records:
                resp['data']['records'].append({
                    'date': record.date,
                    'equipment': settings.EQUIPMENT[record.equipment],
                    'count': record.count,
                    'cost': record.cost,
                    'remark': record.remark,
                    'classes': record.classes,
                    'fare': record.return_fare,
                })
        else:
            resp['code'] = 400
            resp['msg'] = '类型错误~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


# /trade/total/{id}
class TotalTradeAPIView(APIView):
    """个人总计"""

    def get(self, request, id):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        try:
            agent = Agent.objects.get(id=id, status=1)
        except:
            resp['code'] = 400
            resp['msg'] = '无此代理信息~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        trades = Trade.objects.filter(agent=agent, status=1, finance_check=1, manager_check=1).all().aggregate(
            Sum('price'), Sum('collection'),
            Sum('no_collection'), Sum('profits'),
            Sum('generated_cost'), Sum('no_cost'),
            Sum('out_fare'), Sum('in_fare'),
            Sum('generated_commission'), Sum('no_commission'))

        total_price = trades['price__sum']
        total_collection = trades['collection__sum']
        total_no_collection = trades['no_collection__sum']
        total_profits = trades['profits__sum']
        total_generated_cost = trades['generated_cost__sum']
        total_no_cost = trades['no_cost__sum']
        total_out_fare = trades['out_fare__sum']
        total_in_fare = trades['in_fare__sum']
        total_generated_commission = trades['generated_commission__sum']
        total_no_commission = trades['no_commission__sum']

        cabinet = Trade.objects.filter(agent=agent, status=1, finance_check=1, manager_check=1)

        eight_cabinet = cabinet.filter(equipment='0').all().aggregate(Sum('count'))[
            'count__sum']
        sixteen_stand_cabinet = \
            cabinet.filter(equipment='1').all().aggregate(Sum('count'))[
                'count__sum']
        sixteen_integrated_cabinet = \
            cabinet.filter(equipment='2').all().aggregate(Sum('count'))[
                'count__sum']
        thirty_two_cabinet = cabinet.filter(equipment='3').all().aggregate(Sum('count'))[
            'count__sum']
        forty_eight_cabinet = cabinet.filter(equipment='4').all().aggregate(Sum('count'))[
            'count__sum']
        power_bank = cabinet.filter(equipment='5').all().aggregate(Sum('count'))[
            'count__sum']
        league = cabinet.filter(equipment='6').all().aggregate(Sum('count'))[
            'count__sum']

        resp['data']['agent'] = agent.customer_name
        resp['data']['price'] = total_price if total_price else 0
        resp['data']['collection'] = total_collection if total_collection else 0
        resp['data']['no_collection'] = total_no_collection if total_no_collection else 0
        resp['data']['profits'] = total_profits if total_profits else 0
        resp['data']['total_generated_cost'] = total_generated_cost if total_generated_cost else 0
        resp['data']['total_no_cost'] = total_no_cost if total_no_cost else 0
        resp['data']['total_out_fare'] = total_out_fare if total_out_fare else 0
        resp['data']['total_in_fare'] = total_in_fare if total_in_fare else 0
        resp['data']['total_generated_commission'] = total_generated_commission if total_generated_commission else 0
        resp['data']['total_no_commission'] = total_no_commission if total_no_commission else 0
        resp['data']['league'] = league if league else 0
        resp['data']['8'] = eight_cabinet if eight_cabinet else 0
        resp['data']['16-1'] = sixteen_stand_cabinet if sixteen_stand_cabinet else 0
        resp['data']['16-2'] = sixteen_integrated_cabinet if sixteen_integrated_cabinet else 0
        resp['data']['32'] = thirty_two_cabinet if thirty_two_cabinet else 0
        resp['data']['48'] = forty_eight_cabinet if forty_eight_cabinet else 0
        resp['data']['power_bank'] = power_bank if power_bank else 0

        return Response(resp)


# /trade/all/
class AllTradeAPIView(APIView):
    """全部总计"""

    def post(self, request):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}

        req = json.loads(request.body)
        type = req['type'] if 'type' in req else "1"
        page = req['page'] if 'page' in req else 0
        page_size = req['page_size'] if 'page_size' in req else 15

        resp['data']['total'] = []

        # 按日查询
        if type == '1':
            trades_obj = Trade.objects.filter(status=1, finance_check=1, manager_check=1)

        # 按月查询
        elif type == '2':
            trades_obj = Trade.objects.filter(status=1, finance_check=1, manager_check=1).extra(
                select={"date": "DATE_FORMAT(date, '%%Y-%%m')"})
        else:
            resp['code'] = 400
            resp['msg'] = '查询失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        try:
            trades = trades_obj.values('date').annotate(price=Sum('price'), eq_count=Sum(
                'count'), collection=Sum('collection'), no_collection=Sum('no_collection'),
                                                        generated_commission=Sum('generated_commission'),
                                                        no_commission=Sum('no_commission'),
                                                        generated_cost=Sum('generated_cost'),
                                                        no_cost=Sum('no_cost'),
                                                        out_fare=Sum('out_fare'),
                                                        in_fare=Sum('in_fare'),
                                                        profits=Sum('profits'),
                                                        league_count=Sum('count', filter=Q(
                                                            equipment='6')),
                                                        eight_eq_count=Sum('count', filter=Q(
                                                            equipment='0')),

                                                        sixteen_stand_eq_count=Sum(
                                                            'count',
                                                            filter=Q(
                                                                equipment='1')),
                                                        sixteen_integrated_eq_count=Sum(
                                                            'count',
                                                            filter=Q(
                                                                equipment='2')),
                                                        thirty_two_eq_count=Sum(
                                                            'count',
                                                            filter=Q(
                                                                equipment='3')),
                                                        forty_eight_eq_count=Sum(
                                                            'count',
                                                            filter=Q(
                                                                equipment='4')),
                                                        power_bank_eq_count=Sum(
                                                            'count',
                                                            filter=Q(
                                                                equipment='5')),
                                                        ).values(
                'date', 'price', 'eq_count', 'collection', 'no_collection', 'generated_commission', 'no_commission',
                'generated_cost', 'no_cost', 'out_fare', 'in_fare', 'league_count', 'eight_eq_count', 'profits',
                'sixteen_stand_eq_count', 'sixteen_integrated_eq_count', 'thirty_two_eq_count',
                'forty_eight_eq_count', 'power_bank_eq_count').order_by(
                'date')

            if page != 0:
                trades, pages = Page(page, page_size, trades)
                resp['data']['pages'] = pages
            else:
                trades = trades.all()
            for trade in trades:
                resp['data']['total'].append(
                    {
                        'date': '{0}'.format(trade['date']),
                        'price': trade['price'] if trade['price'] else 0,
                        'eq_count': trade['eq_count'] if trade['eq_count'] else 0,
                        'collection': trade['collection'] if trade['collection'] else 0,
                        'no_collection': trade['no_collection'] if trade['no_collection'] else 0,
                        'generated_commission': trade['generated_commission'] if trade['generated_commission'] else 0,
                        'no_commission': trade['no_commission'] if trade['no_commission'] else 0,
                        'generated_cost': trade['generated_cost'] if trade['generated_cost'] else 0,
                        'no_cost': trade['no_cost'] if trade['no_cost'] else 0,
                        'out_fare': trade['out_fare'] if trade['out_fare'] else 0,
                        'in_fare': trade['in_fare'] if trade['in_fare'] else 0,
                        'profits': trade['profits'] if trade['profits'] else 0,
                        'league_count': trade['league_count'] if trade['league_count'] else 0,
                        'eight_eq_count': trade['eight_eq_count'] if trade['eight_eq_count'] else 0,
                        'sixteen_stand_eq_count': trade['sixteen_stand_eq_count'] if trade[
                            'sixteen_stand_eq_count'] else 0,
                        'sixteen_integrated_eq_count': trade['sixteen_integrated_eq_count'] if trade[
                            'sixteen_integrated_eq_count'] else 0,
                        'thirty_two_eq_count': trade['thirty_two_eq_count'] if trade['thirty_two_eq_count'] else 0,
                        'forty_eight_eq_count': trade['forty_eight_eq_count'] if trade['forty_eight_eq_count'] else 0,
                        'power_bank_eq_count': trade['power_bank_eq_count'] if trade['power_bank_eq_count'] else 0
                    }
                )

        except Exception as e:
            print(e)
            resp['code'] = 400
            resp['msg'] = '查询失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)
        return Response(resp)


# /trade/check/{id}/
class CheckAPIView(APIView):
    """审核"""
    permission_classes = [IsAuthenticated, Check]

    def post(self, request, id):
        resp = {'code': 200, 'msg': '审核成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        # 1-通过 2-拒绝
        type = req['type'] if 'type' in req else 1
        user = request.user
        if user.user_type == 3:
            try:
                trade = Trade.objects.get(id=id, status=1, finance_check=1, manager_check=0)
                if type == 1:
                    trade.manager_check = 1
                elif type == 2:
                    trade.status = 2
                    resp['msg'] = '拒绝成功~'
                else:
                    resp['code'] = 400
                    resp['msg'] = '操作无效~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
                trade.save()
            except:
                resp['code'] = 400
                resp['msg'] = '该条明细不存在~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        elif user.user_type == 2:
            try:
                trade = Trade.objects.get(id=id, status=1, finance_check=0, manager_check=0)
                if type == 1:
                    trade.finance_check = 1
                elif type == 2:
                    trade.status = 2
                    resp['msg'] = '拒绝成功~'
                else:
                    resp['code'] = 400
                    resp['msg'] = '操作无效~'
                    resp['success'] = False
                    return Response(resp, status.HTTP_400_BAD_REQUEST)
                trade.save()
            except:
                resp['code'] = 400
                resp['msg'] = '该条明细不存在~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        else:
            resp['code'] = 400
            resp['msg'] = '用户权限不足~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)
        return Response(resp)


# /trade/cost/save/
class CostSaveAPIView(APIView):
    permission_classes = [IsAuthenticated, IsManagerAdminUser]
    """修改价目表"""

    def post(self, request):
        resp = {'code': 200, 'msg': '操作成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)

        date = getCurrentTime(format="%Y-%m-%d")
        old_cost = CostDetails.objects.filter(status=1).last()

        eight_cabinet = req['eight_cabinet'] if 'eight_cabinet' in req else old_cost.eight_cabinet
        sixteen_cabinet = req['sixteen_cabinet'] if 'sixteen_cabinet' in req else old_cost.sixteen_cabinet
        sixteen_cabinet_oneBody = req[
            'sixteen_cabinet_oneBody'] if 'sixteen_cabinet_oneBody' in req else old_cost.sixteen_cabinet_oneBody
        thirty_two_cabinet = req['thirty_two_cabinet'] if 'thirty_two_cabinet' in req else old_cost.thirty_two_cabinet
        forty_eight_cabinet = req[
            'forty_eight_cabinet'] if 'forty_eight_cabinet' in req else old_cost.forty_eight_cabinet
        power_bank = req['power_bank'] if 'power_bank' in req else old_cost.power_bank

        try:
            cost = CostDetails.objects.get(date=date, status=1)
            cost.eight_cabinet = eight_cabinet
            cost.sixteen_cabinet = sixteen_cabinet
            cost.sixteen_cabinet_oneBody = sixteen_cabinet_oneBody
            cost.thirty_two_cabinet = thirty_two_cabinet
            cost.forty_eight_cabinet = forty_eight_cabinet
            cost.power_bank = power_bank
            cost.update_time = getCurrentTime()
            cost.save()

        except:
            CostDetails.objects.create(date=date, eight_cabinet=eight_cabinet, sixteen_cabinet=sixteen_cabinet,
                                       sixteen_cabinet_oneBody=sixteen_cabinet_oneBody,
                                       thirty_two_cabinet=thirty_two_cabinet,
                                       forty_eight_cabinet=forty_eight_cabinet,
                                       power_bank=power_bank)

        return Response(resp)


# /trade/cost/show/
class CostShowAPIView(APIView):
    """成本价目表"""

    def get(self, request):
        resp = {'code': 200, 'msg': '操作成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        cost = CostDetails.objects.last()
        if not cost:
            resp['code'] = 400
            resp['msg'] = '暂无数据~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)
        resp['data'] = {
            "date": cost.date, "eight_cabinet": cost.eight_cabinet, "sixteen_cabinet": cost.sixteen_cabinet,
            "sixteen_cabinet_oneBody": cost.sixteen_cabinet_oneBody, "thirty_two_cabinet": cost.thirty_two_cabinet,
            "forty_eight_cabinet": cost.forty_eight_cabinet, "power_bank": cost.power_bank
        }

        return Response(resp)


# /trade/check/list/
class CheckListAPIView(APIView):
    """待审核列表"""
    permission_classes = [IsAuthenticated, Check]

    def get(self, request):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = request.GET
        user = request.user
        page = req['page'] if 'page' in req else 0
        page_size = req['page_size'] if 'page_size' in req else 15

        resp['data']['trades'] = []
        try:
            if user.user_type == 2:
                trades = Trade.objects.filter(status=1, finance_check=0, manager_check=0)

            elif user.user_type == 3:
                trades = Trade.objects.filter(status=1, finance_check=1, manager_check=0)

            else:
                resp['code'] = 400
                resp['msg'] = '用户权限不足~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

        except:
            resp['code'] = 400
            resp['msg'] = '查询失败~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        if page != 0:
            trades, pages = Page(page, page_size, trades)
            resp['data']['pages'] = pages

        else:
            trades = trades.all()

        if trades:
            for trade in trades:
                resp['data']['trades'].append({
                    'agentId': trade.agent.id,
                    'tradeId': trade.id,
                    'date': trade.date,
                    'count': trade.count,
                    'price': trade.price,
                    'equipment': trade.equipment,
                    'collection': trade.collection,
                    'no_collection': trade.no_collection,
                    'profits': trade.profits,
                    'generated_commission': trade.generated_commission,
                    'no_commission': trade.no_commission,
                    'generated_cost': trade.generated_cost,
                    'no_cost': trade.no_cost,
                    'out_fare': trade.out_fare,
                    'in_fare': trade.in_fare,
                    'fiance_check': trade.finance_check,
                    'manager_check': trade.manager_check
                })
        else:
            resp['code'] = 400
            resp['msg'] = '暂无数据~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        return Response(resp)


class WebQueryAPIView(APIView):
    """网页查看售后信息"""

    def get(self, request):
        resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = request.GET
        company = req['company'] if 'company' in req else 0
        review_status = req['review_status'] if 'review_status' in req else ''
        delivery_status = req['delivery_status'] if 'delivery_status' in req else ''
        search = req['search'] if 'search' in req else ''
        sort = req['sort'] if 'sort' in req else 0

        if company != '':
            if type(company) == str:
                company = int(company)

        if review_status != '':
            if type(review_status) == str:
                review_status = int(review_status)

        if delivery_status != '':
            if type(delivery_status) == str:
                delivery_status = int(delivery_status)

        if sort != '':
            if type(sort) == str:
                sort = int(sort)

        if sort == 0:
            info_obj = ReturnFrom.objects
            if search:
                info_obj = info_obj.filter(return_num__icontains=search)
        elif sort == 1:
            info_obj = ReissuePB.objects
            if search:
                info_obj = info_obj.filter(reissue_num__icontains=search)
        else:
            resp['code'] = 400
            resp['msg'] = 'sort参数错误~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        if review_status:
            try:
                infos = info_obj.filter(status=1, review_status=review_status, bs_type=company)
            except:
                resp['code'] = 400
                resp['msg'] = '暂无数据~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        elif delivery_status:
            try:
                infos = info_obj.filter(status=1, bs_type=company, delivery_status=delivery_status)
            except:
                resp['code'] = 400
                resp['msg'] = '暂无数据~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

        elif delivery_status and review_status:
            try:
                infos = info_obj.filter(status=1, bs_type=company, delivery_status=delivery_status,
                                        review_status=review_status)
            except:
                resp['code'] = 400
                resp['msg'] = '暂无数据~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

        else:
            try:
                infos = info_obj.filter(status=1, bs_type=company)
            except:
                resp['code'] = 400
                resp['msg'] = '暂无数据~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)

        infos = infos.all()
        lists = []
        if sort == 0:
            infos = infos.order_by(
                '-return_id')
            for info in infos:
                devices = getDevices(info)
                return_form = {
                    'id': info.return_id,
                    'return_num': info.return_num,
                    'receipt_num': info.receipt_num,
                    'return_type': getTag(info.return_type, 2),
                    'bs_type': getTag(info.bs_type, 3),
                    'date': info.date,
                    'address': info.address,
                    'review_status': getTag(info.review_status, 0),
                    'delivery_status': getTag(info.delivery_status, 1),
                    'delivery_num': info.delivery_num,
                    'reason': info.reason,
                    'devices': devices,
                }
                lists.append(return_form)
        if sort == 1:
            infos = infos.order_by(
                '-reissue_id')
            for info in infos:
                reissue_form = {
                    'id': info.reissue_id,
                    'reissue_num': info.reissue_num,
                    'bs_type': getTag(info.bs_type, 3),
                    'date': info.date,
                    'address': info.address,
                    'review_status': getTag(info.review_status, 0),
                    'delivery_status': getTag(info.delivery_status, 1),
                    'delivery_num': info.delivery_num,
                }
                lists.append(reissue_form)
        resp['data'] = lists

        return Response(resp)


# class WebPowerBankQueryAPIView(APIView):
#     """网页查看补宝信息"""
#
#     def get(self, request):
#         resp = {'code': 200, 'msg': '查询成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
#         req = request.GET
#         company = req['company'] if 'company' in req else 0
#         review_status = req['review_status'] if 'review_status' in req else ''
#         delivery_status = req['delivery_status'] if 'delivery_status' in req else ''
#         search = req['search'] if 'search' in req else ''
#
#         reissue_pb_obj = ReissuePB.objects
#         if search:
#             reissue_pb_obj = reissue_pb_obj.filter(return_num__icontains=search)
#
#         if review_status:
#             try:
#                 infos = reissue_pb_obj.filter(status=1, review_status=review_status, bs_type=company).order_by(
#                     '-return_id')
#             except:
#                 resp['code'] = 400
#                 resp['msg'] = '暂无数据~'
#                 resp['success'] = False
#                 return Response(resp, status.HTTP_400_BAD_REQUEST)
#         elif delivery_status:
#             try:
#                 infos = reissue_pb_obj.filter(status=1, bs_type=company, delivery_status=delivery_status).order_by(
#                     '-return_id')
#             except:
#                 resp['code'] = 400
#                 resp['msg'] = '暂无数据~'
#                 resp['success'] = False
#                 return Response(resp, status.HTTP_400_BAD_REQUEST)
#
#         elif delivery_status and review_status:
#             try:
#                 infos = reissue_pb_obj.filter(status=1, bs_type=company, delivery_status=delivery_status,
#                                               review_status=review_status).order_by(
#                     '-return_id')
#             except:
#                 resp['code'] = 400
#                 resp['msg'] = '暂无数据~'
#                 resp['success'] = False
#                 return Response(resp, status.HTTP_400_BAD_REQUEST)
#
#         else:
#             try:
#                 infos = reissue_pb_obj.filter(status=1, bs_type=company).order_by(
#                     '-return_id')
#             except:
#                 resp['code'] = 400
#                 resp['msg'] = '暂无数据~'
#                 resp['success'] = False
#                 return Response(resp, status.HTTP_400_BAD_REQUEST)
#
#         infos = infos.all()
#         lists = []
#         for info in infos:
#             return_form = {
#                 'id': info.reissue_id,
#                 'reissue_num': info.reissue_num,
#                 'bs_type': getTag(info.bs_type, 3),
#                 'date': info.date,
#                 'address': info.address,
#                 'review_status': getTag(info.review_status, 0),
#                 'delivery_status': getTag(info.delivery_status, 1),
#                 'delivery_num': info.delivery_num,
#             }
#             lists.append(return_form)
#         resp['data'] = lists
#
#         return Response(resp)


class AfterConfirmAPIView(APIView):
    """审核与发货"""

    def post(self, request):
        resp = {'code': 200, 'msg': '确认成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        order_num = req['order_num'] if 'order_num' in req else ''
        # sort 0-审核 1-发货
        sort = req['sort'] if 'sort' in req else 1
        delivery_num = req['delivery_num'] if 'delivery_num' in req else ''

        tag = order_num[:2]
        if tag == 'JS' or tag == 'QD':
            try:
                info = ReturnFrom.objects.get(return_num=order_num, delivery_status=0, status=1)
            except Exception as e:
                resp['code'] = 400
                resp['msg'] = '暂无该退换货数据或已经发货~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        elif tag == 'PB':
            try:
                info = ReissuePB.objects.get(reissue_num=order_num, delivery_status=0, status=1)
            except Exception as e:
                resp['code'] = 400
                resp['msg'] = '暂无该补宝数据或已经发货~'
                resp['success'] = False
                return Response(resp, status.HTTP_400_BAD_REQUEST)
        else:
            resp['code'] = 400
            resp['msg'] = '订单号错误~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)
        if sort == 0:
            info.review_status = 1
            resp['msg'] = '审核成功'
        if sort == 1:
            info.delivery_num = delivery_num
            info.delivery_status = 1
            resp['msg'] = '发货成功'
        else:
            resp['code'] = 400
            resp['msg'] = 'sort参数数据~'
            resp['success'] = False
            return Response(resp, status.HTTP_400_BAD_REQUEST)

        info.save()
        return Response(resp)
